/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
/* eslint-disable no-tabs */
import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken, setToken, setPermissions, setUserRoles, hasPermission, getTheme, setTheme, setIsShowMenu, setGisBizType, setLanguage } from './utils/auth' // 验权
import { getMessageByCode } from './utils/responseMessage'
import { GetUsrPermissions } from './api/user'
import i18n from './i18n/index.js'

const whiteList = ['/login', '/greenWaveOptimizeNew', '/deviceNew', '/operaterecordNew', '/overviewNew/index'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  let cloudrbac = to.query.cloudrbac
  if (cloudrbac) {
    let theme = to.query.kiaf_theme
    if (theme) {
      if (theme instanceof Array) {
        theme = theme[0]
      }
      switchTheme(theme)
    }
    let gisBizType = to.query.gisBizType
    let isShowMenu = to.query.isShowMenu
    if (isShowMenu !== undefined) {
      setIsShowMenu(isShowMenu)
    }
    // 隐藏菜单
    store.dispatch('SetMenuVisible', isShowMenu)
    if (gisBizType) {
      store.dispatch('SetGisBizType', gisBizType)
      setGisBizType(gisBizType)
    }
    let host = window.location.origin
    // if (!host.includes('https')) {
    //   host = host.replace('http', 'https')
    // }
    let page = window.location.href.split('?')[0].split('/#/')[1]
    let url = `${host}/openatc/oauth2/cloudrbaurl?bizPage=${page}`
    window.location.href = url
    // window.location.href = 'http://192.168.14.182:10003/openatc/oauth2/cloudrbaurl'
  } else {
    let token = to.query.token
    if (token) {
      setToken(token)
    }
    let gisBizType = to.query.gisBizType
    let isShowMenu = to.query.isShowMenu
    if (isShowMenu !== undefined) {
      setIsShowMenu(isShowMenu)
    } else {
      setIsShowMenu(true)
    }
    // 隐藏菜单
    store.dispatch('SetMenuVisible', isShowMenu)
    if (gisBizType) {
      store.dispatch('SetGisBizType', gisBizType)
      setGisBizType(gisBizType)
    }
    let theme = to.query.theme
    if (theme) {
      if (theme instanceof Array) {
        theme = theme[0]
      }
      switchTheme(theme)
    }
    let language = to.query.language
    if (language) {
      setLanguage(language)
    }
  }
  if (from.path === '/overview/index' && from.params.flag) {
    Message.error('您当前正处于手动状态，请先退出手动！')
  } else {
    NProgress.start()
    if (getToken()) {
      if (to.path === '/login') {
        next({ path: '/home' })
        NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
      } else {
        if (whiteList.indexOf(to.path) !== -1 || whiteList.indexOf(store.getters.devicePath) !== -1) {
        // iframe父页面回退至首页和跳转至设备详情时，不作下面逻辑处理
          next()
          return
        }
        if (Object.keys(store.getters.userInfo).length === 0) {
          store.dispatch('GetInfo').then(res => { // 拉取用户信息
            let roleNames = res.roleNames
            let userName = res.user_name
            setUserRoles(roleNames)
            GetUsrPermissions(userName).then(data => {
              if (data.data.success !== true) {
                Message.error(getMessageByCode(data.data.code, i18n.locale))
                return
              }
              let permissions = data.data.data
              let permissionList = permissions.map(item => {
                return item.permission_code
              })
              // set cache
              setPermissions(permissionList)
              let routes = router.options.routes
              let route = getRoute(routes, to.path)
              let permissionStr = route.permission
              if (!permissionStr) {
                next()
              }
              if (hasPermission(permissionStr)) {
                next()
              } else {
                next({ path: from.path })
              }
              // next()
            })
          }).catch((err) => {
            store.dispatch('FedLogOut').then(() => {
              Message.error(err || 'Verification failed, please login again')
              next({ path: '/home' })
            })
          })
        } else {
          let routes = router.options.routes
          let route = getRoute(routes, to.path)
          let permissionStr = route.permission
          if (!permissionStr) {
            next()
          }
          if (hasPermission(permissionStr)) {
            next()
          } else {
            next({ path: from.path })
            NProgress.done()
          }
        }
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next('/login')
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})

function getRoute (routes, path) {
  let res = ''
  for (let route of routes) {
    let rp = route.path
    if (rp === path) {
      res = route
      break
    } else {
      if (route.children) {
        let crp = route.children[0].path
        if (rp + crp === path) {
          res = route
          break
        }
      }
    }
  }
  return res
}

function switchTheme (val) {
  let theme = getTheme()
  if (val === theme) {
    return false
  }
  if (val === 'dark') {
    switchToDark()
  } else {
    switchToLight()
  }
}

function switchToDark () {
  setTheme('dark')
  // location.reload()
}

function switchToLight () {
  setTheme('light')
  // location.reload()
}
